<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
    <meta content="telephone=no" name="format-detection" />
    <!-- 留作将来统一添加 -->
    <TEMPLATE>${TEMPLATE}</TEMPLATE>
    <title>课程详情</title>
    <link rel="stylesheet" type="text/css" href="../../css/api.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/aui.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/index.css">
    <link rel="stylesheet" type="text/css" href="../../css/data-flex.min.css">
    <style type="text/css">
        .vueApp {
            padding-top: 10px;
            background-color: #5AC2FF;
            min-height: 100vh;
            overflow-y: auto;
        }
        .item-box {
            padding: 10px 15px;
        }
        .item {
            position: relative;
            border-radius: 8px;
            overflow: hidden;
            width: 100%;
            height: 200px;
        }
        .item img {
            width: 100%;
            height: 200px;
        }
        .progress {
            margin-top: 5px;
            height: 4px;
            background-color: #fff;
            width: 100%;
            border-radius: 2px;
        }
        .progress .content {
            background-color: #5AC2FF;
            height: 4px;
            border-radius: 2px;
        }
        .info-box {
            position: absolute;
            left: 0;
            right: 0;
            bottom: 0;
            height: 60px;
            background:linear-gradient(180deg,rgba(0,0,0,0) 0%,rgba(0,0,0,0.8) 98%);
            padding: 24px 15px 10px;
        }
        .level2 {
            color: #fff;
            height: 20px;
        }
        .level2 p {
            font-size: 0.8rem;
            color: #fff;
            font-weight: bolder;
        }
        .level2 p.percent {
            font-size: 0.7rem;
            font-weight: normal;
        }
        .level2 img {
            width: 20px;
            height: 20px;
        }

        .tips {
            padding: 0 15px;
            font-size: 13px;
            font-weight: 400;
            color: rgba(255, 255, 255, 0.76);
            line-height: 13px;
        }
    </style>
</head>
<body>
    <div class="vueApp" v-cloak>
        <div class="tips" v-show="endDate">课程有效期至:{{formatTime(endDate, 'date')}}</div>
        <div v-for="item,index in listData" class="item-box">
            <div class="item" @click="handleItem(item)">
                <img :src="item.coursePic" alt="">
                <div class="info-box">
                    <div class="level2" data-flex="main:justify cross:center">
                        <!-- <p class="one-line">{{ item.courseName + '（可下载资源'+ item.courseSize +'M）'}}</p> -->
                        <p class="one-line">{{ item.courseName }}</p>
                        <!-- <p class="percent" v-if="item.status == 1 && item.loading">排队中</p>
                        <p class="percent" @click="item.progress < 100 ? handleCancleDownload(index, event) : ''" v-else-if="item.loading">
                            {{ item.progress >= 100 ? '已下载' : item.progress +'%' }}
                            {{ item.progress >= 100 ? '已下载' : '取消' }}
                        </p>
                        <p class="percent" @click="handleDownload(index, event)" v-else-if="item.isUpdate">有更新</p>
                        <img v-else @click="handleDownload(index, event)" src="../../image/course/download.png" alt=""> -->
                    </div>
                    <!-- <div v-if="item.loading" class="progress">
                        <div :style="'width:'+ item.progress + '%'" class="content"></div>
                    </div> -->
                </div>
            </div>
        </div>
    </div>
</body>
<script type="text/javascript" src="../../script/api.js"></script>
<script type="text/javascript" src="../../script/service/service-tool.js"></script>
<script type="text/javascript" src="../../script/service/service-app.js"></script>
<script type="text/javascript" src="../../script/service/service-user.js"></script>
<script type="text/javascript" src="../../script/service/service-logic.js"></script>
<script type="text/javascript" src="../../script/jquery.min.js"></script>
<script type="text/javascript" src="../../script/vue.min.js"></script>
<script type="text/javascript" src="../../script/localFile.js"></script>
<script type="text/javascript">
    // html 的引号一律为双引号(""),js 为单引号('')
    var USER, $S, vm, pageParam;
    var DownloadMap = {}, DownloadCourseKey = 'download_course_id',
        userMap = {}, userLoadKey = '';
    apiready = function(){
        $S = SERVICE();
        USER = USER();
        userLoadKey = 'course_'+USER.Get('custId');
        // 获取已缓存的小节
        DownloadMap = api.getPrefs({key: DownloadCourseKey, sync: true});
        DownloadMap = JSON.parse(DownloadMap || '{}');
        userMap = DownloadMap[userLoadKey] || {};
        console.log(JSON.stringify(api.pageParam) + '=====pageParam');
        pageParam = api.pageParam;
        fnInit();

        initLocalDownload();
    };

    // 初始化
    function fnInit() {
        vm = new Vue({
            el: '.vueApp',
            data: {
                endDate: '',
                listData: [],
                pageSize: 100
            }
        });
        load();
        getEndDate();
    }

    function getEndDate() {
        var url = 'course/findCourseEndDate';
        var params = {
            'courseId': pageParam.id
        };
        var callback = function(data) {
            vm.endDate = data.endDate;
        };
        POST(url, params, callback);
    }


    /**
     * 产生随机整数，包含下限值，但不包括上限值
     * @param {Number} lower 下限
     * @param {Number} upper 上限
     * @return {Number} 返回在下限到上限之间的一个随机整数
     */
    function random(lower, upper) {
        return Math.floor(Math.random() * (upper - lower)) + lower;
    }


    function load() {
        getPageData();
    }

    // 获取页面数据
    function getPageData() {
        var url = 'course/findCourseChild';
        var params = {
            'courseParentId': pageParam.id,
            'pageSize': vm.pageSize
        };
        var callback = function(data) {
            var listData = data.listData;
            for(var i = 0; i < listData.length; i ++) {
                var item = listData[i];
                item.progress = 0;
                item.courseSize = (i+1)*13+7.8;// random(1, 101);
                item.isUpdate = false;
                item.downloadDate = userMap[item.id] || '';
            }
            api.refreshHeaderLoadDone();
            vm.listData = listData;
            if(vm.listData.length > 0)
                getUnitDownloadData(0);
        };
        POST(url, params, callback);
    }

    // 取消下载
    function handleCancleDownload(index, e) {
        e && fnStopPropagation(e);
        var list = deepCopy(vm.listData);
        var item = list[index];
        if(item.loading == true && item.progress < 100) {
            item.loading = false;
            item.progress = 0;
            vm.listData = list;
            api.sendEvent({
                name: 'cancle_downloading'
            });
            api.removeEventListener({
                name: 'courseDownload_'+item.id
            });
        }
    }

    function handleDownload(index, e) {
        e && fnStopPropagation(e);
        var list = deepCopy(vm.listData);
        var item = list[index];
        item.loading = true;
        if(item.allKeys.length == 0) {
            // 无下载内容
            // item.progress = 100;
            item.loading = false;
            fnToast('小节无下载内容');
        }else {
            // 开始下载
            var callbackEvent = 'courseDownload_'+item.id;
            addDownloadListenner(index);
            api.sendEvent({
                name: 'course_insert_download',
                extra: {
                    data: item.loadData,
                    downloadKey: item.id,
                    callback: callbackEvent
                }
            })
        }
        vm.listData = list;
    }

    function addDownloadListenner(index) {
        var list = deepCopy(vm.listData);
        var item = list[index];
        var _index = index*1;
        var callbackEvent = 'courseDownload_'+item.id;
        api.addEventListener({
            name: callbackEvent
        }, function(ret) {
            var status = ret.value.status, progress = ret.value.progress;
            var list = deepCopy(vm.listData),
                item = list[_index];
            // item.loading = true;
            // console.log(status +'==='+ progress);
            if(!item.loading) return;
            if(status == 1) {
                // 排队中
                item.status = 1;
            }else if(status == 2) {
                // 正在下载
                item.status = 2;
                item.progress = (progress*100).toFixed(2);
            }else if(status == 3) {
                // 下载完成
                item.progress = 100;
                updateDownloadDate(item.id);
            }
            vm.listData = list;
        });
        // 是否排队
        api.sendEvent({
            name: 'course_is_download',
            extra: {
                id: item.id,
                callback: callbackEvent
            }
        });
    }

    // 更新本地缓存
    function updateDownloadDate(id) {
        userMap[id] = new Date().getTime()+'';
        DownloadMap[userLoadKey] = userMap;
        api.setPrefs({
            key: DownloadCourseKey,
            value: JSON.stringify(DownloadMap)
        });
    }

    // 获取单元可下载数据
    // 获取课程下载状态
    function getUnitDownloadData(index) {
        var sender = vm.listData[index];
        var url = 'course/preDownLoad';
        var params = {
            id: sender.id,
            resourceLastTime: sender.downloadDate
        };
        var callback = function(data) {
            var allKeys = getAllKeys(data);
            var list = deepCopy(vm.listData);
            if(allKeys.length > 0 && sender.downloadDate) {
                list[index].isUpdate = true;
                // 有更新
            }else if(sender.downloadDate) {
                list[index].progress = 100;
                list[index].loading = true;
            }
            // 下载数据
            list[index].loadData = data;
            list[index].allKeys = allKeys;
            addDownloadListenner(index);
            vm.listData = list;
            index += 1;
            // 获取下一个小节的数据
            // if(index < vm.listData.length)
            //     getUnitDownloadData(index);
        };
        POST(url, params, callback);
        // $S.POST(url, params, function(ret) {
        //     if(ret && ret.status == 200) {
        //         callback(ret.data);
        //     }
        // });
    }

    // 全部下载
    function headerFn() {
        vm.listData.forEach(function(item, index) {
            var _i = index*1,
                loading = !!!item.loading;
            setTimeout(function() {
                console.error(loading + '===='+ _i);
                loading && handleDownload(_i);
            }, 100*index)
        })
    }

    // 点击item
    function handleItem(item) {
        var params = {
                name: 'course_win',
                url: './course_win.html',
                pageParam: {
                    id: item.id
                },
                slidBackEnabled: false
            };
            fnOpenWin(params);
            return;
        if(item.loading && item.progress >= 100) {
            var params = {
                name: 'course_win',
                url: './course_win.html',
                pageParam: {
                    id: item.id
                },
                slidBackEnabled: false
            };
            fnOpenWin(params);
        }else {
            fnToast('下载完成才能进入');
        }
    }
</script>
</html>